const url = require('url')

function get302(u) {
    const lib = u.startsWith('https') ? require('https') : require('http');
    let req = lib.request({
        method: 'Get',
        host: url.parse(u).host,
        path: u
    }, res => {
        if (res.statusCode == 302) {
            console.log(res.statusCode)
            console.log(res.headers.location)
            return res.headers.location
        } else {
            return u
        }
    })

    req.setHeader('User-Agent', userAgent)
    req.end()
}

function getOption(u) {
    let c = {
        method: 'Get',
        host: url.parse(u).host,
        path: url.parse(u).path,
    }
    return c;
}

function getUrl(u) {
    var p = new Promise(function(resolve, reject) {
        const lib = u.startsWith('https') ? require('https') : require('http');
        let req = lib.request(getOption(u), res => {
            let buf
            res.on('data', function(d) {
                buf = buf ? Buffer.concat([buf, d], buf.length + d.length) : d
            })
            res.on('end', () => {
                if (res.headers['content-encoding'] && res.headers['content-encoding'].indexOf('gzip') != -1) {
                    const zlib = require('zlib')
                    zlib.gunzip(buf, function(err, result) {
                        if (err) {
                            console.log(err)
                        }
                        buf = result
                        resolve(buf, res)
                    })
                } else {
                    resolve(buf, res)
                }
            })
            res.on('error', (err) => reject(err))
        })
        const userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0'
        req.setHeader('User-Agent', userAgent)
        req.end()
    })
    return p;
}

let getStatusCode = function(u) {
    const lib = u.startsWith('https') ? require('https') : require('http');
    lib.get(u, res => {
        console.log(res.statusCode)
        return res.statusCode
    })
}

exports.getStatusCode = getStatusCode
exports.get302 = get302
exports.getUrl = getUrl